<template>
  <div class="app-container">

    <!-- 添加或修改出入库单据对话框 -->
    <el-form ref="form" :model="form" :rules="rules" label-width="80px">
      <el-form-item label="仓库" prop="storeId">
        <el-select v-model="form.storeId" placeholder="请选择仓库" clearable>
          <el-option v-for="store in warehouse" :key="store.id" :value="store.id" :label="store.storeName"/>
        </el-select>
      </el-form-item>
      <el-form-item label="出入库时间" prop="busiDate" label-width="100px">
        <el-date-picker clearable
                        v-model="form.busiDate"
                        type="date"
                        value-format="yyyy-MM-dd"
                        :picker-options="pickerOptions"
                        placeholder="请选择出入库时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"/>
      </el-form-item>
    </el-form>

    <template>
      <el-button type="text" @click="openOut()">添加明细</el-button>

      <el-dialog title="物品列表" :visible.sync="outerVisible" width="1200px">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" label-width="68px">
          <el-form-item label="关键字" prop="keyword">
            <el-input
              v-model="queryParams.params.keyword"
              placeholder="请输入名称/品牌/规格/描述"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="分类" prop="categoryId">
            <treeselect style="width: 150px;"
                        v-model="queryParams.categoryId"
                        :options="tree"
                        :normalizer="normalizer"
                        :show-count="true"
                        placeholder="请选择分类"
                        @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>


        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
              v-hasPermi="['team:goods:add']"
            >新增
            </el-button>
          </el-col>
        </el-row>


        <el-table v-loading="loading" :data="commodityList" >
          <el-table-column
            type="index"
            :index="indexMethod"
            label="序号">
          </el-table-column>
          <el-table-column label="物品名称" align="center" prop="goodsName" show-overflow-tooltip/>
          <el-table-column label="封面" align="center" prop="goodsCover">
            <template slot-scope="scope">
              <image-preview :src="scope.row.goodsCover"  style="width:100px;height:50px;"/>
            </template>
          </el-table-column>
          <el-table-column label="分类" align="center" prop="categoryName"/>
          <el-table-column label="品牌" align="center" prop="brand"show-overflow-tooltip/>
          <el-table-column label="规格" align="center" prop="spec" show-overflow-tooltip/>
          <el-table-column label="描述" align="center" prop="goodsDesc" show-overflow-tooltip/>
          <el-table-column label="数量" align="center" prop="amounts"/>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-plus"
                @click="addGoodList(scope.row)"
                v-hasPermi="['team:goods:edit']"
              >选择此物品
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <el-dialog
          width="30%"
          title="新增"
          :visible.sync="innerVisible"
          append-to-body>
          <el-form ref="addform" :model="form" :rules="rules" label-width="80px">
            <el-form-item label="物品名称" prop="goodsName">
              <el-input v-model="form.goodsName" placeholder="请输入物品名称" maxlength="50"
                        show-word-limit
                        clearable/>
            </el-form-item>
            <el-form-item label="封面" prop="goodsCover">
              <image-upload v-model="form.goodsCover" limit="1"/>
            </el-form-item>
            <el-form-item label="分类" prop="categoryId">
              <treeselect style="width: 150px;"
                          v-model="form.categoryId"
                          :options="tree"
                          :normalizer="normalizer"
                          :show-count="true"
                          placeholder="请选择分类"
              />
            </el-form-item>
            <el-form-item label="品牌" prop="brand">
              <el-input v-model="form.brand" placeholder="请输入品牌" maxlength="50"
                        show-word-limit
                        clearable/>
            </el-form-item>
            <el-form-item label="规格" prop="spec">
              <el-input v-model="form.spec" placeholder="请输入规格" maxlength="50"
                        show-word-limit
                        clearable/>
            </el-form-item>
            <el-form-item label="描述" prop="goodsDesc">
              <el-input type="textarea" v-model="form.goodsDesc" placeholder="请输入描述" maxlength="200"
                        autosize
                        show-word-limit
                        clearable/>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="SaveGoods()">确 定</el-button>
            <el-button @click="handleShowDown()">取 消</el-button>
          </div>
        </el-dialog>

        <div slot="footer" class="dialog-footer">
          <el-button @click="outerVisible = false">取 消</el-button>
        </div>
      </el-dialog>
    </template>


    <template>
      <el-table
        :data="goodsList"
        border
        style="width: 100%">
        <el-table-column
          prop="id"
          label="序号"
          width="180">
        </el-table-column>
        <el-table-column
          prop="name"
          label="物品"
          width="180">
        </el-table-column>
        <el-table-column
          prop="price"
          label="价格">
          <template slot-scope="scope">
            <el-input-number v-model="scope.row.price" :precision="2" :step="0.1" ></el-input-number>
          </template>
        </el-table-column>
        <el-table-column
          prop="number"
          label="数量">
          <template slot-scope="scope">
            <el-input-number v-model="scope.row.number" @change="handleChange" :min="1" label="请输入数量"></el-input-number>
          </template>
        </el-table-column>
        <el-table-column
          prop="subtotal"
          label="小计">
          <template slot-scope="scope">
            <el-input v-model="scope.row.subtotal" disabled></el-input>
          </template>
        </el-table-column>
        <el-table-column
          label="操作">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.$index, goodsList)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </template>

    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="cancel">关闭</el-button>
    </div>
  </div>
</template>

<script>
import {listBill, getBill, delBill, addBill, updateBill} from "@/api/team/bill";
import {outBill} from "../../../api/team/bill";
import {listStore} from "../../../api/team/store";
import {listAll} from "../../../api/team/category";
import {addGoods, listGoods} from "../../../api/team/goods";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import IconSelect from "@/components/IconSelect";

export default {
  name: "Bill",
  components: {Treeselect, IconSelect},
  data() {
    return {
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now();
        }},
      warehouse:[],
      commodityList:[],
      queryParams:{
        params:{
          pageNum: 1,
          pageSize: 10,
          keyword:null,
        }
      },
      outerVisible: false,
      innerVisible: false,
      // 总条数
      total: 0,
      // 商品数量
      goodsList: [],
      // 表单参数
      form: {},
      commodity:{
        price:"",
        number:"",
        subtotal:""
      },
      // 表单校验
      rules: {
        storeId: [
          { required: true, message: '请选择仓库', trigger: 'change' }
        ],
        busiDate: [
          { required: true, message: '请选择日期', trigger: 'change' }
        ],
        goodsName: [
          {required: true, message: '请输入物品名称', trigger: 'blur'}
        ],
        goodsCover: [
          {required: true, message: '请选择封面图片', trigger: 'blur'}
        ],
        categoryId:[
          {required: true, message: '请选择分类', trigger: 'change'}
        ],
        brand: [
          {min: 0, max: 50, message: '不超过50字', trigger: 'blur'}
        ],
        spec: [
          {min: 0, max: 50, message: '不超过50字', trigger: 'blur'}
        ],
        goodsDesc: [
          {min: 0, max: 200, message: '不超过200字', trigger: 'blur'}
        ]
      },
      tree:[],
    };
  },
  created() {
    this.getAll();
    this.getList();
    this.form.type = this.$route.query.type;
    listStore().then(res=>{
      this.warehouse = res.rows;
    })
  },
  computed: {
    ruleFormSpecList(){
      return this.goodsList;
    },
  },
  watch: {
    ruleFormSpecList:{
      handler(){
        this.goodsList.forEach(item=>{
          //计算小计
          if (item.number && item.price){
            this.$set(item, "subtotal", Number(item.number * item.price))
          }
        })
      },
      //因为要监听对象内部的属性，所以要用deep：true
      deep: true
    }
  },
  methods: {
    handleChange(){
    },
    addGoodList(good){
      //先将选中的物品放进goodsList中
      this.commodity.id = good.id;
      this.commodity.name = good.goodsName;
      this.goodsList.push(this.commodity);
      //关闭当前弹窗
      this.outerVisible = false;
    },
    SaveGoods(){
      //调用新增商品的接口
      this.$refs['addform'].validate((valid) => {
        if (valid) {
          addGoods(this.form).then(response => {
            this.$modal.msgSuccess("新增成功");
            this.$refs['addform'].resetFields();
            this.innerVisible = false;
            listGoods(this.queryParams).then(response => {
              this.commodityList = response.rows;
              this.total = response.total;
              this.loading = false;
            });
          });
        }
      });
    },
    handleShowDown(){
      //关闭内嵌弹窗
      this.innerVisible = false
      this.$refs['addform'].resetFields();
    },
    openOut(){
      this.commodity = {
        price:"",
        number:"",
        subtotal:""
      }
      this.outerVisible = true;
      listGoods(this.queryParams).then(response => {
        this.commodityList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    add(row){
      console.log(row)
    },
    indexMethod(index) {
      return index + 1;
    },
    handleAdd(){
      this.innerVisible = true;

    },
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    handleQuery() {
      listGoods(this.queryParams).then(response => {
        this.commodityList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /**查询所有分类*/
    getAll() {
      listAll().then(res => {
        this.tree = this.handleTree(res.data, "id");
        this.allCategory = res.data;
      })
    },
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.categoryName,
        children: node.children
      };
    },
    handleDelete(index, rows){
      rows.splice(index,1);
    },
    /** 查询出入库单据列表 */
    getList() {
      this.form.type = this.$route.query.type;
      this.loading = true;
    },
    // 取消按钮
    cancel() {
      //进行路由跳转
      this.form = {};
      this.goodsList = [];
      this.$refs['form'].resetFields();
      this.$tab.closeOpenPage({path:"/team/bill"});
    },
    /** 提交按钮 */
    submitForm() {
      //判断当前的goodsList是否有数据,没有数据就提示
      if (this.goodsList.length <= 0){
        //如果没有数据就提示消息
        this.$modal.msgError("请添加商品");
      }
      this.form.goods = this.goodsList
      this.$refs["form"].validate(valid => {
        if (valid) {
          if(this.form.type === "0"){
            this.form.type = 0;
            addBill(this.form).then(response => {
              this.$modal.msgSuccess("入库成功");
              this.open = false;
              this.getList();
              this.form = {};
              this.goodsList = [];
              this.$refs['form'].resetFields();
              this.$tab.closeOpenPage({path:"/team/bill"})
            });
          }else{
            this.form.type = 1;
            outBill(this.form).then(response => {
              this.$modal.msgSuccess("出库成功");
              this.open = false;
              this.getList();
              this.form = {};
              this.goodsList = [];
              this.$refs['form'].resetFields();
              this.$tab.closeOpenPage({path:"/team/bill"})
            });
          }
        }
      });
    },
  }
};
</script>
